package core

import (
	"io/ioutil"
	"net"
	"net/http"
	"strings"
	"sync"
	"time"

	"github.com/tidwall/gjson"
	"golang.org/x/net/proxy"
	"golang.org/x/text/encoding/simplifiedchinese"
)

// GetAnAgent 获取代理
func GetAnAgent() []string {
	URL := "http://118.190.215.16:20001/tqip?username=chxu10t&password=chxu10t&userid=10&number=10&time=20200624"
	resp, err := http.Get(URL)
	if err != nil {
		return []string{}
	}
	coding := simplifiedchinese.GB18030.NewDecoder()
	body, err := ioutil.ReadAll(coding.Reader(resp.Body))
	defer resp.Body.Close()
	if err != nil {
		return []string{}
	}
	var proxyList []string
	for _, k := range strings.Split(string(body), ":chxu10t:chxu10t") {
		temp := strings.Split(k, "<br>")
		if len(temp) == 2 {
			proxyList = append(proxyList, temp[1])
		}
	}
	return proxyList
}

// CheckUsable 检测代理可以用
func CheckUsable(str string, strArr *[]string, wg *sync.WaitGroup) {
	defer wg.Done()
	_, _ = proxy.SOCKS5("tcp", str, &proxy.Auth{User: "chxu10t", Password: "chxu10t"}, &net.Dialer{
		Timeout:   3 * time.Second,
		KeepAlive: 3 * time.Second,
	})
	transport := &http.Transport{
		Proxy:               nil,
		TLSHandshakeTimeout: 3 * time.Second,
	}
	client := &http.Client{Transport: transport}
	req, err := http.NewRequest("GET", "https://api.live.bilibili.com/client/v1/Ip/getInfoNew", nil)
	if err != nil {
		return
	}
	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:86.0) Gecko/20100101 Firefox/86.0")
	resp, err := client.Do(req)
	if err != nil {
		return
	}
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	data := gjson.Get(string(body), "data").String()
	if data != "" {
		// 这里保存代理
		*strArr = append(*strArr, str)
	}
}
